package source;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PackHandler extends MessageHandler {
	
	public void handleRequest(Message message) {

       /**
    	* Pattern per trovare il package:
		* #1  4618x [ 5.5K] iroffer 1.0.1  - Stable (v1.0) version
		* ^#(\d+)\s+(.*)x\s+\[\s*(.*[KMGB])\]\s+(.*)
		* 
		* Group(0) = #1  4618x [ 5.5K] iroffer 1.0.1  - Stable (v1.0) version
		* Group(1) = 1
		* Group(2) = 4618
		* Group(3) = 5.5K
		* Group(4) = iroffer 1.0.1  - Stable (v1.0) version
		* 
		*/		
    	String format = "^#(\\d+)\\s+(.*)x\\s+\\[\\s*(.*[KMGB])\\]\\s+(.*)";
    	Pattern pattern = Pattern.compile(format);
    	Matcher matcher = pattern.matcher(message.getMessage());
    	
    	if(matcher.find())
    	{   
    		// pulisco il testo del pacchetto, fa un po' schifo di default...
    		String packText = matcher.group(4).trim().replace("'", "\\'");
    		Database db = Database.getInstance();
    		String query = "INSERT INTO `packets` VALUES (null, null, '" + message.getNetwork() + "', '" + message.getChannel() + "', '" + message.getSender() + "', " + matcher.group(1) + ", " + matcher.group(2) + ", '" + matcher.group(3) + "', '" + packText + "')";   		
    		if(!db.insert(query))
    			System.err.println("Insert error: " + packText);
    	}
    	else
    	{
    		super.handleRequest(message);
    	}
	}
	
}
